package com.zhuqi.handler;

import cn.hutool.core.util.StrUtil;
import com.zhuqi.proto.LogOutMessageProto;
import com.zhuqi.proto.build.LogOutMessageBuild;
import com.zhuqi.proto.cost.MessageProtocolBufEnum;
import com.zhuqi.service.session.Session;
import com.zhuqi.session.messge.MessagePackage;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ZhuQi
 * @ClassName LoggingRequestMessageHandel
 * @Date 2023/1/16 16:35
 * @Version 1.0
 * @Description 登出处理器
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class LogOutRequestMessageHandel extends SimpleChannelInboundHandler<LogOutMessageProto.LogOutMessageRequest> {


	@Resource
	private Session session;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, LogOutMessageProto.LogOutMessageRequest msg) {
		String name = msg.getName();
		session.logOutUser(name);

		MessagePackage messagePackage = new MessagePackage();
		messagePackage.setBusinessCode(MessageProtocolBufEnum.LOG_OUT_RESPONSE_MESSAGE.getCode());
		LogOutMessageProto.LogOutMessageResponse logOutResponseMessage = LogOutMessageBuild.createLogOutResponseMessage(
				true, StrUtil.format("{} 退出成功", name), name);
		messagePackage.setData(logOutResponseMessage.toByteArray());
		ChannelFuture channelFuture = ctx.channel().writeAndFlush(messagePackage);

		channelFuture.addListener((ChannelFutureListener) future -> {
			if (future.isSuccess()) {
				log.info("退出消息发送成功 {};", name);
			}
		});
	}


}
